package com.industry.system.dal.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.industry.framework.common.redis.RedisUtils;
import com.industry.framework.core.cache.GlobleConstants;
import com.industry.framework.core.cache.CoreSystemCacheBuilder;
import com.industry.system.dal.dataobject.SystemUser;
import com.industry.system.dal.db.SystemUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author nbZhuozh
 * @Date 2025-04-07  18:35
 **/
@Service
public class SystemUserInfoCache implements CoreSystemCacheBuilder {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public void cacheAll() {
        LambdaQueryWrapper<SystemUser> eq = Wrappers.lambdaQuery(SystemUser.class).eq(SystemUser::getDelFlag, "0");
        List<SystemUser> systemCodes = systemUserMapper.selectList(eq);
        if(!CollectionUtils.isEmpty(systemCodes)){
            Map<String, List<SystemUser>> collectTentIdMap =
                    systemCodes.stream().collect(Collectors.groupingBy(SystemUser::getId));
            Map<String,String> jksonMap = new HashMap<>();
            collectTentIdMap.forEach((k,v)->{
                String ison = JSON.toJSONString(v, SerializerFeature.WriteDateUseDateFormat);
                //序列化
                jksonMap.put(k,ison);
            });
            RedisUtils.setCacheMap(GlobleConstants.SYSTEM_USER_INFO,jksonMap);
        }
    }


    public List<SystemUser> get(String userId){
        return (List<SystemUser>)
                RedisUtils.getCacheMap(GlobleConstants.SYSTEM_USER_INFO)
                        .get(userId);
    }
}